<template>
	<view class="mine-container" :style="{ height: `${windowHeight + 220}px` }">
		<!-- 个人信息 -->
		<view class="mine-title">个人信息</view>
		<view class="mine-desc">
			<uni-list class="mine-list">
				<uni-list-item title="所属公司" :rightText="userInfo.companyAccountName" />
				<uni-list-item title="所属部门" :rightText="userInfo.dept.deptName" />
				<uni-list-item title="所属岗位" :rightText="userInfo.station" />
				<uni-list-item title="手机号码" :rightText="userInfo.phonenumber" />
				<uni-list-item title="电子邮箱" :rightText="userInfo.email" />
			</uni-list>
			<view class="mine-right">
				<!-- 跳转去修改头像外的个人信息 -->
				<navigator :url="'/pages/mine/info/edit'">
					<view class="edit-img">
						<image class="img" src="@/static/images/mine/editor.png" mode="aspectFit"></image>
					</view>
				</navigator>
				<view class="avatar-img">
					<!-- 跳转去修改头像 -->
					<navigator :url="'/pages/mine/avatar/index'">
						<view class="edit-avatar">
							<image class="img" src="@/static/images/mine/edit-avatar.png" mode="aspectFit"></image>
						</view>
					</navigator>
					<image v-if="userInfo.avatar && userInfo.avatar !== ''" class="img"
						src="@/static/images/mine/avatar.png" mode="aspectFit"></image>
					<!-- 设置一个默认头像 -->
					<image v-else class="img" src="@/static/images/mine/avatar.png" mode="aspectFit"></image>
				</view>
				<view class="name">{{ userInfo.nickName }}</view>
			</view>
		</view>

		<view class="tabs">
			<tabs :list="tabsList" @getTabs="getTabs" />
			<!-- 安全考核 -->
			<view class="tabs-safe" v-if="tabsActive === '安全考核'">
				<view class="title"> 安全考核 </view>

				<view class="desc2">
					<view class="item">
						<view class="item-name">本年度原始积分：</view>
						<view class="item-num">{{ safe.originalIntegral }}</view>
					</view>
					<!-- 	<view class="item">
						<view class="item-name">数据更新时间：</view>
						<view class="item-num">{{ safe.date }}</view>
					</view> -->
					<view class="item">
						<view class="item-name">当前积分：</view>
						<view class="item-num">{{ safe.nowGrade  }}</view>
					</view>
					<!-- 	<view class="item">
						<view class="item-name">数据更新时间：</view>
						<view class="item-num">{{ safe.date }}</view>
					</view> -->
				</view>
			</view>
			<!-- 教育培训 -->
			<view class="tabs-education" v-if="tabsActive === '教育培训'">
				<view class="title"> 教育培训 </view>
				<view class="desc1">
					<view class="item">
						<view class="item-name">本年度参加培训次数：</view>
						<view class="item-num">{{ education.num }} 次</view>
					</view>
				</view>
				<view class="desc1" v-for="(item, index) in educationList" :key="index">
					<view class="item">
						<view class="item-name">培训名称：</view>
						<view class="item-num">{{ item.name }}</view>
					</view>
					<view class="item">
						<view class="item-name">培训日期：</view>
						<view class="item-num">{{ item.date }}</view>
					</view>
					<view class="item">
						<view class="item-name">培训学时：</view>
						<view class="item-num">{{ item.time }} 学时</view>
					</view>
					<view class="item">
						<view class="item-name">培训考分：</view>
						<view class="item-num">{{ item.score }} 分</view>
					</view>
				</view>
			</view>
			<!-- 应急管理 -->
			<!-- 		<view class="tabs-emergency" v-if="tabsActive === '应急管理'">
				<view class="title"> 应急管理 </view>
				<view class="desc2">
					<view class="item-name">应急岗位：</view>
					<view class="item-num">{{ emergency.duty }} </view>
				</view>
				<view class="desc3">
					<view class="item-name">应急职责：</view>
					<view class="item-num">{{ emergency.dutyDesc }} </view>
				</view>
			</view> -->
			<!-- 签字管理 -->
			<view class="tabs-sign" v-if="tabsActive === '签字管理'" style="height: 700rpx;">
				<view>
					<view class="title"> 签字管理 </view>
				</view>

				<view class="desc2">
					<view class="desc1" v-for="(item, index) in signList" :key="index">
						<view class="item">
							<view class="item-name">人员姓名：</view>
							<view class="item-num">{{ item.createBy }}</view>
						</view>
						<view class="item">
							<view class="item-name">是否有效：</view>
							<view class="item-num">{{ item.isDel == "0" ? '有效' :'无效' }}</view>
						</view>
						<view class="item">
							<view class="item-name">上传时间：</view>
							<view class="item-num">{{ item.createTime }} </view>
						</view>
						<view class="item">
							<view class="item-name">设置签字：</view>
							<view class="item-num"><button type="primary" size="mini" class="sign-btn"
									@click="handleSign">点击签字</button>
							</view>
						</view>
						<view class="his-more">
							<text @click="viewSign">查看历史签字</text>
						</view>
					</view>

				</view>
			</view>
			<!-- //签字记录@change="change($event,'showLeft')" -->
			<uni-drawer ref="showLeft" mode="left" class="drawer">
				<view class="close">
					<uni-nav-bar height="65px" shadow left-icon="left" @clickLeft="closeDrawer('showLeft')"
						leftText="返回" rightText="" title="历史签字" />
					<!-- <button @click="closeDrawer('showLeft')"><text class="word-btn-white">关闭Drawer</text></button> -->
				</view>
				<view class="content">

					<!-- style="height: 700rpx;width: 500rpx;" 在弹窗内使用z-paging时，z-paging的父view必须确定宽高（或者z-paging本身确定宽高）  -->
					<view class="desc2">
						<!-- 设置fixed=false代表z-paging非铺满全屏，此时z-paging高度未确定，其父view或z-paging本身必须确定宽高 -->
						<!-- v-if="showPaging"用于控制z-paging的展示，本身在pop-up中已经加了v-if了，但是在微信小程序中无效，会导致页面渲染时pop-up中的内容同时渲染，因此需要额外添加一个v-if -->
						<z-paging ref="paging" :fixed="false" v-model="dataList" @query="queryList">
							<!-- 需要固定在顶部不滚动的view放在slot="top"的view中，如果需要跟着滚动，则不要设置slot="top" -->
							<!-- 注意！此处的z-tabs为独立的组件，可替换为第三方的tabs，若需要使用z-tabs，请在插件市场搜索z-tabs并引入，否则会报插件找不到的错误 -->
							<!-- <template #top>
								<view>doingbu</view>
							</template> -->
							<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
							<scroll-view class="scroll-view-box" scroll-y="true">
								<view class="desc1" v-for="(item,index) in dataList" :key="index"
									@click="itemClick(item,index)">
									<view class="item">
										<view class="item-name">上传时间：</view>
										<view class="item-num">{{item.createTime }} </view>
									</view>

									<view class="item">
										<view class="item-name">历史签字：</view>
										<template v-if="item.fileInfo && item.fileInfo.url">
											<image class="item-img" :src="item.fileInfo.url"></image>

										</template>

									</view>
								</view>
							</scroll-view>

						</z-paging>

					</view>
				</view>



			</uni-drawer>
			<!-- 签字弹窗 -->
			<uni-popup ref="popup" type="center" width="100%" background-color="#fff" height="600px">
				<uni-nav-bar back-text="返回" title="签字"></uni-nav-bar>

				<view style="width: 750rpx ;height: 500rpx;">
					<jp-signature ref="signatureRef"></jp-signature>
				</view>
				<view>
					<button @click="clear">清空</button>
					<button @click="undo">撤消</button>
					<button @click="save">保存</button>
				</view>
				</u-form>
			</uni-popup>
		</view>
		<view class="logout" @click="handleLogout">退出登录</view>
	</view>
</template>

<script>
	import {
		listSign,
		searchIntegralRecord
	} from "@/api/home/index.js"
	import tabs from "@/components/tabs/index";
	export default {
		components: {
			tabs,
		},
		data() {
			return {
				userInfo: {},
				imageValue: [],
				// "应急管理",
				tabsList: ["安全考核", "教育培训", "签字管理"],
				tabsActive: "安全考核", //tabs点击的标题
				//签字记录
				dataList: [],
				//考核记录
				safe: {

				},
				dateRange: [], //时间
				education: {
					num: 2,
				},
				signForm: {
					pageNum: 1,
					pageSize: 1
				},
				signList: [],
				educationList: [{
						name: "安全培训",
						date: "2023-04-28 14:25:23",
						time: 1,
						score: "98"
					},
					{
						name: "作业培训",
						date: "2023-04-28 14:25:23",
						time: 2,
						score: "/"
					},
					{
						name: "作业培训",
						date: "2023-04-28 14:25:23",
						time: 2,
						score: "/"
					},
				],
				emergency: {
					duty: "应急组长",
					dutyDesc: "组长负责整个应急小组的领导工作，并担任组织指挥的角色，确保所有成员能够有效地参与到应急响应中。",
				},
			};
		},
		created() {
			// 获取用户信息
			this.userInfo = uni.getStorageSync("userInfo");
			this.getSpecialDay()
			this.getScord()
		},
		computed: {
			windowHeight() {
				return uni.getSystemInfoSync().windowHeight;
			},
		},
		methods: {
			//查看签字 打开窗口
			viewSign() {
				this.$refs['showLeft'].open()
			},

			// 关闭窗口
			closeDrawer(e) {
				this.$refs[e].close()
			},
			//保存
			save() {
				let config = require('@/config.js')
				// 是否为空画板 无签名

				this.$refs.signatureRef.canvasToTempFilePath({
					success: (res) => {
						// 生成图片的临时路径
						// H5 生成的是base64
						if (res.isEmpty == false) {
							// this.url = res.tempFilePath
							let blob = this.dataURLtoBlob(res.tempFilePath);
							// 拿到文件名
							let fileName = "电子签名.jpg";
							// 2，在转为 file类型
							let file = this.blobToFile(blob, fileName);
							const formData = new FormData();
							formData.append("file", file);

							uni.uploadFile({
								url: `${config.baseUrl}/common/upload`,
								header: {
									'Authorization': 'Bearer ' + uni.getStorageSync(
										'App-Token') //请求头信息
								},
								filePath: res.tempFilePath,
								name: 'file',
								success: (res) => {
									let response = JSON.parse(res.data)
									// @params  status: 状态判断上传文件穿什么type
									let query = {
										type: "59",
										fileId: response.id,
										url: response.url,
										name: response.fileName
									}
									uni.showToast({
										title: "上传成功"
									})
									// this.signObj.url = response.url
									// this.anaValiFormData.fileInfoList = [query]
									// uni.showToast({
									// 	title: `填写成功`,
									// });
									this.$refs.popup.close()

								}
							})
						}
					}
				})
			},

			//1,先将base64转换为blob
			dataURLtoBlob(baseurl) {
				var arr = baseurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			//2,再将blob转换为file
			blobToFile(theBlob, fileName) {
				theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
				theBlob.name = fileName; // 文件名
				return new File([theBlob], fileName, {
					type: theBlob.type,
					lastModified: Date.now(),
				});
			},
			//清除
			clear() {
				this.$refs.signatureRef.clear()
			},
			//撤销按钮
			undo() {
				this.$refs.signatureRef.undo()
			},
			//设置签字
			handleSign() {
				this.$refs.popup.open('center')
			},
			// 格式化日期的辅助函数
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, "0");
				const day = date.getDate().toString().padStart(2, "0");
				// const hours = date.getHours().toString().padStart(2, "0");
				// const minutes = date.getMinutes().toString().padStart(2, "0");
				// const seconds = date.getSeconds().toString().padStart(2, "0");
				return `${year}-${month}-${day}`;
			},
			getSpecialDay() {
				const firstDay = new Date(new Date().getFullYear(), 0, 1);
				// 获取当年的最后一天
				const lastDay = new Date(new Date().getFullYear(), 11, 31);

				let beginTime = this.formatDate(firstDay);

				let lastTime = this.formatDate(lastDay);

				this.dateRange.push(beginTime, lastTime);
			},
			//获取当前用户的积分信息
			async getScord() {
				let query = {
					beginTime: this.dateRange[0],
					endTime: this.dateRange[1],
					userId: this.userInfo.userId
				}
				let res = await searchIntegralRecord(query)
				this.safe = res.rows[0]
				// console.log("获取考核信息", res)
			},
			queryList(pageNum, pageSize) {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageNum: pageNum,
					pageSize: pageSize,
					userId: this.userInfo.userId
				}
				listSign(params).then(res => {
					// 将请求的结果数组传递给z-paging
					this.$refs.paging.complete(res.rows);
				}).catch(res => {
					// 如果请求失败写this.$refs.paging.complete(false);
					// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
					// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
					this.$refs.paging.complete(false);
				})
			},
			// 获取上传状态
			select(e) {
				console.log('选择文件：', e)
				let {
					tempFiles
				} = e

				let query = {
					fileId: tempFiles[0].uuid,
					type: 59,
					name: tempFiles[0].cloudPath
				}
				this.user.userInfo = query
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功')
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			//获取签字管理数据
			async getSignData() {
				let {
					userId
				} = uni.getStorageSync("userInfo")
				this.signForm.userId = userId
				let res = await listSign(this.signForm)
				this.signList = res.rows
			},
			// 当前点击的tabs
			getTabs(val) {
				// console.log(val, "val");
				this.tabsActive = val;
				if (val == '签字管理') {
					this.getSignData()
				}
			},
			handleLogout() {
				this.$modal.confirm("确定注销并退出系统吗？").then(() => {
					this.$store.dispatch("LogOut").then(() => {
						this.$tab.reLaunch("/pages/index");
					});
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.mine-container {
		width: 100%;
		padding: 10rpx 20rpx;
		background: linear-gradient(to bottom,
				rgb(202, 231, 252) 0%,
				rgb(245, 248, 250) 100%);

		.mine-title {
			margin: 20rpx 0;
			font-size: 38rpx;
			font-weight: 700;
			text-align: center;
			letter-spacing: 0.54rpx;
			line-height: 56.24rpx;
			color: rgba(0, 0, 0, 1);
		}

		.mine-desc {
			display: flex;
			width: 100%;
			height: 462rpx;
			border-radius: 40rpx;
			background: rgba(255, 255, 255, 1);
			overflow: hidden;

			.mine-list {
				width: 75%;
				margin-top: 12rpx;

				::v-deep {
					.uni-list-item {
						height: 86rpx;
					}

					.uni-list--border-top {
						height: 0;
					}
				}
			}

			.mine-right {
				.edit-img {
					margin: 18rpx 0 60rpx 110rpx;
					width: 52rpx;
					height: 52rpx;

					.img {
						width: 100%;
						height: 100%;
					}
				}

				.avatar-img {
					position: relative;
					margin: 0 0 54rpx 10rpx;
					width: 160rpx;
					height: 160rpx;

					.img {
						width: 100%;
						height: 100%;
					}

					.edit-avatar {
						z-index: 999;
						position: absolute;
						bottom: 0;
						right: 6rpx;
						width: 60rpx;
						height: 60rpx;

						.img {
							width: 100%;
							height: 100%;
						}
					}
				}

				.name {
					text-align: center;
					font-size: 40rpx;
					font-weight: 400;
					letter-spacing: -1.04rpx;
					line-height: 76.96rpx;
					color: rgba(39, 40, 51, 1);
				}
			}
		}

		.tabs {
			margin: 20rpx 0;
			width: 100%;

			::v-deep {
				.scroll {
					height: 74rpx;
					border-radius: 16rpx;
					background: rgba(255, 255, 255, 0.4);

					.active-item {
						border-radius: 12rpx;
						background: rgba(255, 255, 255, 1);
						font-size: 30rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						line-height: 43.44rpx;
						color: rgba(27, 44, 73, 1);
						border-bottom: 0px solid #000;
					}

					.item {
						font-size: 30rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						line-height: 43.44rpx;
						color: rgba(102, 111, 128, 1);
					}
				}
			}



			.common-class {
				margin-top: 20rpx;
				width: 100%;
				height: 750rpx;
				overflow-y: auto;
				border-radius: 16rpx;
				background: rgba(255, 255, 255, 1);

				.title {
					height: 96rpx;
					text-align: center;
					font-size: 32rpx;
					font-weight: 500;
					letter-spacing: 0rpx;
					line-height: 96rpx;
					color: rgba(0, 0, 0, 1);
					border-bottom: 1rpx solid rgba(242, 242, 242, 1);
				}

				.desc1 {
					padding: 20rpx 32rpx 10rpx;
					border-bottom: 1rpx solid rgba(242, 242, 242, 1);
				}

				.item {
					display: flex;
					height: 60rpx;
					font-size: 28rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 40.54rpx;
					color: rgba(68, 68, 68, 1);

					.item-name {
						margin-right: 5rpx;
					}

					.item-num {
						.sign-btn {
							width: 85px;
							height: 24px;
							font-size: 12px
						}
					}

					.item-img {
						width: 130rpx;
						height: 74rpx;
					}
				}

				.his-more {
					margin-top: 13px;
					text-align: center;
					font-size: 14px;
					font-weight: 400;
					color: rgba(19, 126, 233, 1);
				}
			}

			//历史签字记录
			.drawer {
				::v-deep {
					.uni-navbar--border {
						border-bottom: none;
					}

					.content {
						@extend .common-class;
						height: 100%;

						.desc2 {
							height: 90vh !important;
							width: 100vw !important;
						}
					}

				}
			}

			// 安全考核
			.tabs-safe {
				@extend .common-class;

				.desc2 {
					padding: 20rpx 32rpx 10rpx;
				}
			}

			// 教育培训
			.tabs-education {
				@extend .common-class;
			}

			//签字记录抽屉
			.uni-drawer {
				::v-deep {
					.uni-drawer__content--visible {
						width: 100% !important;
					}
				}

			}


			//个人签字
			.tabs-sign {
				@extend .common-class;

				// height: 400rpx;
				.desc1 {
					padding: 20rpx 32rpx 10rpx;
					border-bottom: none;

				}
			}

			// 应急管理
			.tabs-emergency {
				@extend .common-class;

				.desc2,
				.desc3 {
					padding: 20rpx 32rpx;
					font-size: 28rpx;
					color: rgba(68, 68, 68, 1);

					.item-name {
						margin-right: 5rpx;
						font-weight: 500;
					}

					.item-num {
						font-weight: 400;
					}
				}

				.desc2 {
					display: flex;
				}

				.desc3 {
					.item-name {
						margin-bottom: 30rpx;
					}
				}
			}
		}

		.logout {
			// margin-top: 900rpx;
			border-radius: 40rpx;
			margin: 0 auto;
			width: 60%;
			height: 80rpx;
			background-color: #0ea4f1;
			text-align: center;
			color: #ffffff;
			line-height: 80rpx;
		}
	}
</style>